package com.cenntro.oss.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.cenntro.auth.model.dbo.SysSooidDO;
import com.cenntro.auth.service.SysSooidService;
import com.cenntro.auth.utils.AgentPathUtil;
import com.cenntro.common.base.BaseController;
import com.cenntro.common.model.vo.PageVO;
import com.cenntro.common.model.vo.TreeUtil;
import com.cenntro.common.model.vo.TreeVO;
import com.cenntro.common.util.ConvertorUtils;
import com.cenntro.common.util.NumUtil;
import com.cenntro.common.util.result.PageResult;
import com.cenntro.common.util.result.Result;
import com.cenntro.oss.model.dbo.SysAgentDO;
import com.cenntro.oss.model.vo.AgentDetailsVO;
import com.cenntro.oss.model.vo.AgentVO;
import com.cenntro.oss.service.SysAgentService;
import com.cenntro.oss.valid.Valid;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.ImmutableMap;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(value = "客户查询", tags = { "客户查询" })
@RestController
@RequestMapping("/agent")
public class AgentController extends BaseController {

	@Resource
	private SysAgentService sysAgentService;
	@Resource
	private SysSooidService sysSooidService;

    @RequestMapping(value = "/home")
    public String home(AgentVO agentVO, PageVO pageVO) {
       return RandomStringUtils.random(100);
    }
	/**
	 * 
	 * @return PageResult.List
	 */
//    @RequiresPermissions("/agent/select")
	@ApiOperation(value = "客户查询按id升序", notes = "客户查询")
	@RequestMapping(value = "/selectPage")
	public Result selectPage(AgentVO agentVO, PageVO pageVO) {
		SysAgentDO agent = ConvertorUtils.deepConvert(agentVO, SysAgentDO.class);
		Page<SysAgentDO> page = PageHelper.startPage(pageVO.getPage(), pageVO.getLimit(), true);
		
		String agentPath = AgentPathUtil.getAgentPathByRole(null);
		agent.setAgentPath(agentPath);
//		Subject subject = SecurityUtils.getSubject();
//        int roleType = (Integer)subject.getSession().getAttribute("roleType");
//        if (roleType != 1){
//            SysSooidDO user = (SysSooidDO)subject.getPrincipal();
//            if(roleType == 2){ //
//                agent.setAgentPath(user.getAgentPath());
//            }
//        }
		
		List<SysAgentDO> list = sysAgentService.selectPage(agent);

		list.forEach(ag -> ag.setCity(ag.getCountry() + " " + ag.getCity()));
		return PageResult.ok(list,  page.getTotal());
	}

	/**
	 * 
	 * @return PageResult.List
	 */
	@ApiOperation(value = "客户查询company升序", notes = "客户查询")
	@RequestMapping(value = "/selectPagebySort")
	public Result selectPagebySort(AgentVO agentVO, PageVO pageVO) {
		SysAgentDO agent = ConvertorUtils.deepConvert(agentVO, SysAgentDO.class);
		agent.setSort("sort by company asc");
		Page<SysAgentDO> page = PageHelper.startPage(pageVO.getPage(), pageVO.getLimit(), true);
		String agentPath = AgentPathUtil.getAgentPathByRole(null);
        agent.setAgentPath(agentPath);
		
//		Subject subject = SecurityUtils.getSubject();
//        int roleType = (Integer)subject.getSession().getAttribute("roleType");
//        if (roleType != 1){
//            SysSooidDO user = (SysSooidDO)subject.getPrincipal();
//            if(roleType == 2){ //
//                agent.setAgentPath(user.getAgentPath());
//            }
//        }
		List<SysAgentDO> list = sysAgentService.selectPage(agent);

		return PageResult.ok(list, page.getTotal());
	}

	/**
	 * 客户新增
	 * 
	 * @return
	 */
	
//	@RequiresPermissions("/agent/add")
	@ApiOperation(value = "客户新增", notes = "客户新增")
	@RequestMapping(value = "/insert")
	public Result insert(@Validated(value = { Valid.insert.class }) AgentVO agentVO) {
		SysAgentDO sysAgentDO = sysAgentService.selectOne(ImmutableMap.of("company", agentVO.getCompany()));
		if (StringUtils.isNotBlank(agentVO.getAccount())){
		    SysSooidDO soo = sysSooidService.selectOne(ImmutableMap.of("userName", agentVO.getAccount()));
	        if (sysAgentDO != null) {
	            return Result.error("客户名称已经被使用");
	        } else if (soo != null) {
	            return Result.error("客户帐号已经被使用");
	        }
		} 

//        Subject subject = SecurityUtils.getSubject();
//        int roleType = (Integer)subject.getSession().getAttribute("roleType");
//        if(roleType != 1 && NumUtil.toInt(agentVO.getPid()) == 0){//agent
//            return Result.error("请选择上级客户！");
//        }
		if(AgentPathUtil.getRoleType() > 1 && NumUtil.toInt(agentVO.getPid()) == 0){ //非管理员不能创建客户
		    return Result.error("请选择上级客户！");
		}
		sysAgentService.insert(agentVO);
		return Result.ok();
	}

	/**
	 * 客户修改
	 * 
	 * @return PageResult.List
	 */
	@CrossOrigin
	@ApiOperation(value = "客户修改", notes = "客户修改")
	@RequestMapping(value = "/update")
	public Result update(@Validated(value = { Valid.update.class }) AgentVO agentVO) {
	    SysAgentDO sysAgentDO = null;
	    if(StringUtils.isNotBlank(agentVO.getCompany())){
	        sysAgentDO = sysAgentService.selectOne(ImmutableMap.of("company", agentVO.getCompany()));
	    }
		if (sysAgentDO != null && !agentVO.getId().equals(sysAgentDO.getId())) {
			return Result.error("客户名称已经被使用");
		}
		if(AgentPathUtil.getRoleType() > 1 && NumUtil.toInt(agentVO.getPid()) == 0){ //非管理员不能创建客户
            return Result.error("请选择上级客户！");
        }
		sysAgentService.update(agentVO);
		return Result.ok();
	}

	/**
	 * 客户删除
	 * 
	 * @return PageResult.List
	 */
	@ApiOperation(value = "客户删除", notes = "客户删除")
	@RequestMapping(value = "/delete")
	public Result delete(@Validated(value = { Valid.update.class }) AgentVO agentVO) {
		sysAgentService.deleteById(agentVO.getId());
		return Result.ok();
	}
	/**
     * 客户树形结构查询(下拉菜单)
     * 
     * @return Result.List<treeVO>
     */
    @ApiOperation(value = "客户树形结构查询", notes = "客户树形结构查询")
    @RequestMapping(value = "/selectAgent4Tree")
	public Result selectAgent4Tree(AgentVO agentVO){
        String agentPath = AgentPathUtil.getAgentPathByRole(null);
        SysAgentDO agent = ConvertorUtils.deepConvert(agentVO, SysAgentDO.class);
        agent.setAgentPath(agentPath);
//        Subject subject = SecurityUtils.getSubject();
//        int roleType = (Integer)subject.getSession().getAttribute("roleType");
        
//        if (roleType != 1){
//            SysSooidDO user = (SysSooidDO)subject.getPrincipal();
//            if(roleType == 2){ //
//                agent.setAgentPath(user.getAgentPath());
//            }
//        }
        List<SysAgentDO> list = sysAgentService.selectPage(agent);
        
        List<?> tree = new TreeUtil<SysAgentDO>() {
            @Override
            public boolean isRootId(SysAgentDO e, TreeVO pNode) {
                if (e.getAgentPath().replace(e.getId().toString(), "").equals("0_")) {
                    return true;
                }
                return false;
            }
            @Override
            public boolean isParentId(SysAgentDO e, TreeVO pNode) {
                String[] ids = e.getAgentPath().split("[_-]");
                int index = ArrayUtils.indexOf(ids, pNode.getId().toString());
                return index == (ids.length - 2);
            }
            
            @Override
            public String getRootId(SysAgentDO e, TreeVO pNode) {
                if (e.getAgentPath().replace(e.getId().toString(), "").equals("0_")) {
                    return e.getId().toString();
                } else {
                    return pNode.getRootId();
                }
            }
            @Override
            public void setField(SysAgentDO e, TreeVO treeVO) {
                treeVO.setId(e.getId());
                treeVO.setName(e.getCompany());
            }
        }.toTree(null, list);
        return Result.ok(tree);
	}
    

//  /**
//   * 组织机构树
//   * 
//   * @param agentId
//   * @return
//   */
//  @RequestMapping("/tree")
//  @CrossOrigin
//  public Result agentTree(Integer agentId) {
//      if (agentId != null && agentId > 0) {
//          List<AgentTreeVO> list = sysAgentService.agentTree(agentId);
//          return Result.ok(list);
//      } else {
//          return Result.error("参数错误");
//      }
//  }

    /**
     * 公司信息
     * 
     * @param agentId
     * @return
     */
    @RequestMapping("/details")
    @CrossOrigin
    public Result details(Integer agentId) {
        SysAgentDO agentDO = sysAgentService.selectById(agentId);
        if (agentDO != null) {
            AgentDetailsVO detailsVO = ConvertorUtils.deepConvert(agentDO, AgentDetailsVO.class);
            return Result.ok(detailsVO);
        } else {
            return Result.error("公司信息不存在");
        }

    }

    /**
     * 修改联系人
     * 
     * @param userName
     * @param linkName
     * @return
     */
    @RequestMapping("/updateLinkName")
    @CrossOrigin
    public Result updateLinkName(Integer agentId, String linkMan) {
        if (agentId != null && StringUtils.isNotBlank(linkMan)) {
            SysAgentDO agent = new SysAgentDO();
            agent.setId(agentId);
            agent.setLinkMan(linkMan);
            Integer count = sysAgentService.update(agent);
            if (count > 0) {
                return Result.ok();
            }
        }
        return Result.error("参数错误");

    }

    /**
     * 修改logo
     * 
     * @param agentId
     * @return
     */
    @RequestMapping("/updateLogo")
    @CrossOrigin
    public Result updateLogo(Integer agentId, HttpServletRequest request) {
        if (agentId != null && agentId > 0) {
            return sysAgentService.updateLogo(agentId, request);
        } else {
            return Result.error("参数错误");
        }
    }
    
	
}
